#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>


int main()
{
    printf("stdin->fd: %d\n", stdin->_fileno);
    printf("stdout->fd: %d\n", stdout->_fileno);
    printf("stderr->fd: %d\n", stderr->_fileno);


    char buffer[1024];
    ssize_t s = read(0, buffer, sizeof(buffer));
    if(s < 0) return 1;
    buffer[s] = '\0';
    printf("echo : %s\n", buffer);

    const char *msg = "hello Linux\n";
    write(1, msg, strlen(msg));
    write(2, msg, strlen(msg));

    umask(0);
   //等价与fopen的a打开方式 
    int fd=open("file.txt",O_WRONLY|O_CREAT|O_APPEND,0666);

    //等价于fopen的w打开方式
    //int fd=open("file.txt",O_WRONLY|O_CREAT|O_TRUNC,0666);
    //int fd=open("file.txt",O_WRONLY|O_CREAT,0666);
    //int fd=open("file.txt",O_WRONLY);//会创建失败
    //int fd=open("file.txt",O_WRONLY|O_CREAT);//创建的文件没有权限
    if(fd<0)
    {
        perror("open");
        exit(-1);
    }

    const char* buf="hello linux";
    write(fd,buf,strlen(buf));

    lseek(fd,0,SEEK_SET);
    int file_size=lseek(fd,0,SEEK_END);
    printf("file_size:%d\n",file_size);
    close(fd);


    int ffd=open("file.txt",O_RDONLY,0666);
    if(ffd<0)
    {
        perror("open");
        exit(-1);
    }
    
    char ret[1024]={0};
    read(ffd,ret,strlen(buf));

    //lseek(ffd,0,SEEK_SET);
    //int file_size=lseek(ffd,0,SEEK_END);
    //printf("file_size:%d\n",file_size);
    
    fprintf(stdout,"%s\n",ret);
    close(ffd);

    //FILE* fp=fopen("log.txt","w");
    //FILE* fp=fopen("log.txt","a");
   // if(fp == NULL)
   // {
   //     perror("fopen");
   //     exit(-1);
   // }
   // 
   // const char* msg="hello linux\n";
   // //fwrite(msg,strlen(msg)+1,1,fp);
   // //不需要加上1，字符串已\0结尾只是你c语言规定的，和我文件没关系
   // fwrite(msg,sizeof(char),strlen(msg),fp);
   //
   // //fseek(fp, 0, SEEK_END);      //将文件指针指向该文件的最后
   // //int file_size = ftell(fp);       //根据指针位置，此时可以算出文件的字符数
   // //fseek(fp, 0, SEEK_SET);

   // fclose(fp);
    
    //FILE* rfp=fopen("log.txt","r");
    //if(fp==NULL)
    //{
    //    perror("fopen");
    //    exit(-1);
    //}
    //char ret[1024]={0};
    //fread(ret,sizeof(char),12,rfp);
    //printf("%s\n",ret);

    //fclose(fp);

    return 0;
}
